<?php

/**
 * 更新订单信息
 */
// 定义网站根目录.
define('ROOT_PATH', realpath(__DIR__ . '/../'));
// 定义网站应用目录.
define('APP_PATH', ROOT_PATH . '/App/');
// 定义网站缓存文件目录.
define('CACHE_PATH', ROOT_PATH . '/Caches/');

// 加载应用入口文件.
require_once APP_PATH . 'App.php';
App::autoload();

$order_file = ROOT_PATH . '/Data/order.csv';

if (!is_file($order_file)) {
    echo "{$order_file} is not found\n";
    exit;
}

$handle = fopen($order_file, "r");
if ($handle === false) {
    echo "open {$order_file} failed\n";
    exit;
}

$datalist = [];
$i = 0;
while (($data = fgetcsv($handle, 5000, ",")) !== false) {
    $i++;
    if ($i == 1) {
        // 过滤第一行标题行
        continue;
    }

    // 订单id
    $order_id = $data[25];
    $product_id = $data[3];
    // 订单状态
    $order_status = $data[8];

    // 如果订单未导入myorder 则导入
    $row = \Db::instance()->getRow("select `id`,`order_id` from `myorder` where `order_id`='$order_id'");
    if (!$row) {
        \Db::instance()->insert('myorder', ['order_id' => $order_id]);
    }

    $key = $order_id . '-' . $product_id;
    $datalist[$key][] = [
        'order_id' => $order_id, // 订单id
        'product_id' => $product_id, // 商品id
        'create_time' => $data[0],
        'title' => $data[2], // 商品标题
        'payment' => $data[12], // 付款金额
        'pre_commission' => $data[13], // 预估佣金
        'pre_red_packet' => \Config\System::$site['rmRate'] * $data[13],
        'account_payment' => $data[14], // 结算金额
        'account_commission' => $data[15], // 结算佣金
        'account_time' => $data[16], // 结算时间
        'red_packet' => \Config\System::$site['rmRate'] * $data[15],
        'order_status' => $data[8], // 订单状态=结算/付款/失效
    ];
}

if ($datalist) {
    foreach ($datalist as $k => $d) {
        $order_id = $d[0]['order_id'];
        $product_id = $d[0]['product_id'];

        $dtmp = $d;
        foreach ($d as $n => $dt) {
            // 过滤掉订单失效
            if ($dt['order_status'] == '订单失效') {
                unset($d[$n]);
            }
        }

        if ($d) {
            $d = array_values($d);
        }

        $param = [
            'order_id' => $d ? $d[0]['order_id'] : $dtmp[0]['order_id'],
            'product_id' => $d ? $d[0]['product_id'] : $dtmp[0]['product_id'],
            'create_time' => $d ? $d[0]['create_time'] : $dtmp[0]['create_time'],
            'title' => $d ? $d[0]['title'] : $dtmp[0]['title'],
            'payment' => $d ? array_sum(array_column($d, 'payment')) : array_sum(array_column($dtmp, 'payment')),
            'pre_commission' => $d ? array_sum(array_column($d, 'pre_commission')) : array_sum(array_column($dtmp, 'pre_commission')),
            'pre_red_packet' => $d ? array_sum(array_column($d, 'pre_red_packet')) : array_sum(array_column($dtmp, 'pre_red_packet')),
            'account_payment' => $d ? array_sum(array_column($d, 'account_payment')) : array_sum(array_column($dtmp, 'account_payment')),
            'account_commission' => $d ? array_sum(array_column($d, 'account_commission')) : array_sum(array_column($dtmp, 'account_commission')),
            'account_time' => $d ? $d[0]['account_time'] : $dtmp[0]['account_time'],
            'red_packet' => $d ? array_sum(array_column($d, 'red_packet')) : array_sum(array_column($dtmp, 'red_packet')),
            'order_status' => getOrderStatus($dtmp),
        ];

        $where = "`order_id`='$order_id' and `product_id`='$product_id'";
        if (\Db::instance()->count("select count(1) from `orderlist` where $where")) {
            $ret = \Db::instance()->updateByWhere('orderlist', $param, $where);
            if ($ret === false) {
                echo "{$where} update failed\n";
            } else {
                echo "{$where} update success\n";
            }
        } else {
            $ret = \Db::instance()->insert('orderlist', $param);
            if ($ret) {
                echo "{$where} insert success\n";
            } else {
                echo "{$where} insert failed\n";
            }
        }
    }
}

// 更新订单用户关联
$sql = "select * from  `wx_user`";
$rs = \Db::instance()->getList($sql);

foreach ($rs as $r) {
    $openid = $r['openid'];
    $weixinid = $r['weixinid'];
    if ($weixinid) {
        $param = [
            'openid' => $openid,
        ];
        $ret = \Db::instance()->updateByWhere('relation_user', $param, "`user_id`='$weixinid'");
        if (!$ret) {
            echo "wxid: {$weixinid}, up relation_user failed\n";
        }
    }
}

// 更新status和total_packet
$maxId = 0;
$order = "`id` asc";
$limit = 50;

while (true) {
    $where = "`id`>'$maxId'";
    //$where = "`id`> '$maxId' && `status`<> 6";
    $sql = "select `id`,`order_id`,`openid`,`user_id`,`status`,`packet_time` from `myorder` where $where order by $order limit $limit";
    $rs = \Db::instance()->getList($sql);
    if (!$rs) {
        echo "end\n";
        break;
    }

    $order_ids = array_column($rs, 'order_id');
    $relation = getUserIds($order_ids);

    foreach ($rs as $r) {
        $id = $maxId = $r['id'];
        $order_id = $r['order_id'];
        $tb_uid = substr($order_id, -6);
        $user_id = $r['user_id'] ? $r['user_id'] : (isset($relation[$tb_uid]) ? $relation[$tb_uid]['user_id'] : '');
        $openid = $r['openid'] ? $r['openid'] : (isset($relation[$tb_uid]) ? $relation[$tb_uid]['openid'] : '');
        
        $v = new \Logic\Order($id, '', $order_id);
        $ret = $v->getOrderInfo();

        $param = [
            'openid' => $openid,
            'user_id' => $user_id,
            'status' => $r['packet_time'] ? 6 : $ret['status'],
            'total_packet' => $ret['total_packet'],
        ];

        \Db::instance()->updateById('myorder', $param, $id);
    }
}

/**
 * 查询tb_uid关联的user_id
 */
function getUserIds($order_ids = []) {
    $tb_uids = [];
    foreach ($order_ids as $order_id) {
        $tb_uids[] = substr($order_id, -6);
    }

    $id_string = "('" . implode("','", $tb_uids) . "')";
    $sql = "select `openid`,`user_id`,`tb_uid` from `relation_user` where `tb_uid` in $id_string";
    return \Db::instance()->getList($sql, 'tb_uid');
}

/**
 * 返回订单状态
 */
function getOrderStatus($order_info = []) {
    $order_status = '订单失效';
    foreach ($order_info as $d) {
        if ($d['order_status'] != '订单失效') {
            $order_status = '订单结算';
            break;
        }
    }
    if ($order_status == '订单失效') {
        return '订单失效';
    }

    $order_status = '订单结算';
    foreach ($order_info as $d) {
        if ($d['order_status'] == '订单付款' || $d['order_status'] == '订单成功') {
            $order_status = '订单付款';
            break;
        }
    }
    return $order_status;
}
